var ejs = require("ejs");
const path = require("path");
const fs = require("fs");
const db = require("../../middleware/db");
const funTool = require("../../tool/funTool");
const logsUtil = require("../../tool/logs");
const { sys_menu, sys_model, sys_model_field, sys_form, sys_form_field, op, querySql } = require("../../middleware/baseModel");

module.exports = {
  async getFrontTemplatePath(menu_id) {
    let fileName = "";
    let model_id = "";
    let modelName = "custom_template";

    let sysMenuRow = await sys_menu.findOne({ where: { id: menu_id } });
    if (sysMenuRow) {
      fileName = sysMenuRow.path;
      model_id = sysMenuRow.model_id;

      let modelRow = await sys_model.findOne({ where: { id: model_id } });
      if (modelRow) {
        modelName = modelRow.key;
      }
    }

    return { modelName, fileName, model_id };
  },

  async autoModel(id, uuid) {




    let modelRow = await sys_model.findOne({ where: { id: id } });
    if (modelRow) {
      let modelTempPath = `../model/${modelRow.key}_${uuid}.js`
      try {
        let modelTxt = await fs.readFileSync(path.join(__dirname, "../../config/template/model.ejs"), "utf-8");
        let columnsRows = await sys_model_field.findAll({ where: { model_id: id }, order: [["sort", "asc"]] });
        if (columnsRows) {
          let html = ejs.render(modelTxt, { columns: columnsRows, table_name: modelRow.key }, { rmWhitespace: true });

          await fs.writeFileSync(path.join(__dirname, `../model/${modelRow.key}.js`), html);
          await fs.writeFileSync(path.join(__dirname, modelTempPath), html);
        }
      }
      catch (e) {
        logsUtil.errError(e.message);
        fs.unlinkSync(modelTempPath); // 重新删除文件
      }
    }

  },

  async autoDb(id, uuid) {



    let modelRow = await sys_model.findOne({ where: { id: id } });
    if (modelRow) {
      let modelPath = path.join(__dirname, `../model/${modelRow.key}_${uuid}.js`);
      try {
        // 延时调用 重新生成数据库
        let modelDb = require(modelPath);
        await modelDb.sync({ force: true });

        fs.unlinkSync(modelPath); // 重新删除文件
      } catch (e) {
        logsUtil.errError(e.message);
        fs.unlinkSync(modelPath); // 重新删除文件
      }
    }

  },

  async createForm(menu_id, model_id) {
    let formRow = await sys_form.findOne({ where: { menu_id, model_id } });

    if (formRow) {
      await sys_form_field.destroy({ where: { form_id: formRow.id } }); // 删除所有字段
    } else {
      let modelRow = await sys_model.findOne({ where: { id: model_id } });
      let name = modelRow.name;
      formRow = await sys_form.create({ name, menu_id, model_id });
    }

    // 创建表单
    const menuRow = await sys_menu.findOne({ where: { id: menu_id } });
    if (formRow && menuRow) {
      let form_id = formRow.id;
      let fieldRows = await sys_model_field.findAll({ where: { model_id: model_id }, order: [["sort", "asc"]] });
      if (fieldRows && fieldRows.length > 0) {
        for (let i = 0; i < fieldRows.length; i++) {
          let { id: model_field_id, name: model_field_name, control, data_type } = fieldRows[i];

          await sys_form_field.create({ form_id, model_field_id, model_field_name, control, is_show_edit: 1, is_edit_disable: 0, is_show_list: data_type === "TEXT" ? 0 : 1, is_show_seach: 1, sort: i });
        }
      }
    }
  },

  async autoController(id) {
    let modelRow = await sys_model.findOne({ where: { id: id } });
    if (modelRow) {
      let { key: table_name } = modelRow.toJSON();
      let controllerTxt = await fs.readFileSync(path.join(__dirname, "../../config/template/controller.ejs"), "utf-8", { rmWhitespace: true });
      let html = ejs.render(controllerTxt, { table_name });

      await fs.writeFileSync(path.join(__dirname, "../controller_admin/" + table_name + ".js"), html);
    }
  },

  // 生成前端文件Api
  async autoFrontEndApi(menu_id) {
    let formRow = await sys_menu.findOne({ where: { id: menu_id } });
    if (formRow) {
      let { api_path } = formRow;
      let api_path_index = api_path.lastIndexOf("/");
      let folderPath = path.join(__dirname, `../../admin/src/api/${api_path.substr(0, api_path_index)}`);
      let filePath = api_path.substr(api_path_index, api_path.length - 1);

      let Apihtml = "";

      let { modelName, fileName } = await this.getFrontTemplatePath(menu_id);
      if (fileName) {
        let controllerTxt = await fs.readFileSync(path.join(__dirname, "../../config/template//vue_file/apiServer.ejs"), "utf-8");
        Apihtml = ejs.render(controllerTxt, { modelName, fileName });
      }

      //创建文件夹
      await funTool.mkdirsSync(folderPath);
      // 创建api文件
      await fs.writeFileSync(`${folderPath}/${filePath}`, Apihtml);
    }
  },

  // 创建page 下Vue文件
  async autoFrontEndVue(menu_id) {
    let formRow = await sys_menu.findOne({ where: { id: menu_id } });
    if (formRow) {
      let { component, api_path } = formRow;
      let component_index = component.lastIndexOf("/");
      let folderRoot = `${component.substr(0, component_index)}`;

      let { fileName, model_id } = await this.getFrontTemplatePath(menu_id);
      if (fileName) {
        let sysFormRow = await sys_form.findOne({ where: { menu_id, model_id } });
        if (sysFormRow && sysFormRow.id) {
          let sysFormFields = await sys_form_field.findAll({
            where: { form_id: sysFormRow.id },
            include: [
              {
                association: sys_form_field.associations.field,
                attributes: ["key", "name", "data_type", "default_value"],
              },
            ],
            order: [["sort", "asc"]],
          });
          let newcolumnsRows = sysFormFields.map((p) => {
            let newRow = p.toJSON();

            // 设置默认值
            if (newRow.field && newRow.field.default_value) {
              newRow.default_value = newRow.field.default_value;
            } else {
              newRow.default_value = "";
            }

            newRow.name = newRow.model_field_name;

            if (newRow.field && newRow.field.key) {
              newRow.key = newRow.field.key;
              newRow.data_type = newRow.field.data_type;
            }

            newRow.control = JSON.parse(newRow.control);
            if (newRow.control.interfaceType === "本地数据") {
              newRow.source = newRow.control.localData || [];
            } else {
              newRow.source = [];
            }
            return newRow;
          });

          let controllerTxt = await fs.readFileSync(path.join(__dirname, "../../config/template//vue_file/page.ejs"), "utf-8");

          let pageHtml = ejs.render(controllerTxt, { api_path, fileName, columns: newcolumnsRows, model_id }, { rmWhitespace: true });

          let folderPath = path.join(__dirname, `../../admin/src/view/${folderRoot}`);

          //创建文件夹
          await funTool.mkdirsSync(folderPath);

          await fs.writeFileSync(`${folderPath}/${fileName}.vue`, pageHtml);
        }
      }
    }
  },
  // 删除文件
  async destroyApiFile(menu_id) {
    try {
      let formRow = await sys_menu.findOne({ where: { id: menu_id } });
      if (formRow) {
        let model_id = formRow.model_id;
        let modelRow = await sys_model.findOne({ where: { id: model_id } });
        if (modelRow) {
          let modelKey = modelRow.key;

          // 删除后端 controller
          let controller_admin_path = path.join(__dirname, "../controller_admin/" + modelKey + ".js");
          if (await funTool.isExist(controller_admin_path)) {
            fs.unlinkSync(controller_admin_path);
          }

          // 删除后端 modelPath
          let modelPath = path.join(__dirname, "../model/" + modelKey + ".js");
          if (await funTool.isExist(modelPath)) {
            fs.unlinkSync(modelPath);
          }

          // 删除数据库
          await querySql(`DROP TABLE ${modelKey}`);
        }
      }
    } catch (error) {
      logsUtil.errError(error.message);
      return false;
    }

    return true;
  },

  async destroyVueFile(menu_id) {
    let menuRow = await sys_menu.findOne({ where: { id: menu_id } });

    if (menuRow) {
      let { id, component, api_path, model_id } = menuRow;
      // 删除前端page
      if (component) {
        let pagePath = path.join(__dirname, `../../admin/src/view/${component}`);
        if (await funTool.isExist(pagePath)) {
          fs.unlinkSync(pagePath);
        }
      }

      // 删除前端apiServe
      if (api_path) {
        let apiPath = path.join(__dirname, `../../admin/src/api/${api_path}`);
        if (await funTool.isExist(apiPath)) {
          fs.unlinkSync(apiPath);
        }
      }

      // 删除表单
      let formRow = await sys_form.findOne({ where: { model_id, menu_id: id } });
      if (formRow) {
        await sys_form_field.destroy({ where: { form_id: formRow.id } });
        await formRow.destroy({});
      }
    }
  },
};
